package com.p1.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.p1.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")//produces:指定响应体返回类型和编码
    @ResponseBody//加上这个注解就不会走视图解析器,会直接返回一个字符串
     public String json1() throws JsonProcessingException {

        //ObjectMapper:创建一个jackson的对象映射器，用来解析数据
        ObjectMapper mapper=new ObjectMapper();

        //创建一个对象
        User user=new User("光头强",18,"男");

        String value = mapper.writeValueAsString(user);//能将数据解析为字符串向前台输出


        //由于如果每个类都加上produces的话,比较麻烦,所以在Controller22中可以统一解决乱码
        return value;
     }

}
